package me.magicall.test.reflect.proxy;

import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import me.magicall.test.db.tmpdb.TmpResultSet;

public class Util {
	static final String GET = "get";
	static final int GET_LEN = GET.length();

	static final String SET = "set";
	static final int SET_LEN = SET.length();

	static final int METHOD_NAME_2ND = GET_LEN + 1;

	@SuppressWarnings("unchecked")
	static final Class[] EMPTY_CLASS_ARR = {};

	static ResultSet select(final String sql) {
		//TODO
		if (sql.equals("getList")) {
			return new TmpResultSet(DB_COLUMNS, DB_USER);
		} else {
			final List<String[]> datas = new ArrayList<String[]>(DB_USER.length);
			for (final String[] user : DB_USER) {
				if (user[0].equals(sql)) {
					datas.add(user);
				}
			}
			return new TmpResultSet(DB_COLUMNS, datas.toArray(new String[datas.size()][]));
		}
	}

	static String getterOrSetterNameToFieldName(final Method method) {
		return getterOrSetterNameToFieldName(method.getName());
	}

	static String getterOrSetterNameToFieldName(final String methodName) {
		if (methodName.startsWith(GET) || methodName.startsWith(SET)) {
			return Character.toLowerCase(methodName.charAt(Util.GET_LEN)) + methodName.substring(Util.METHOD_NAME_2ND);
		} else {
			return methodName;
		}
	}

	static String fieldNameToGetterName(final String fieldName) {
		return GET + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
	}

	static String cammalNameTo_Name(final String cammalName) {
		final StringBuilder sb = new StringBuilder();
		final int len = cammalName.length();
		for (int i = 0; i < len; i++) {
			final char c = cammalName.charAt(i);
			if (Character.isUpperCase(c)) {
				sb.append("_").append(Character.toLowerCase(c));
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}

	static Method[] getters(final Class<?> c) {
		final Method[] methods = c.getMethods();
		final List<Method> list = new ArrayList<Method>(methods.length);
		for (final Method m : methods) {
			final String name = m.getName();
			if (name.startsWith(GET)) {
				if (!name.equals("getClass")) {
					list.add(m);
				}
			}
		}
		return list.toArray(new Method[list.size()]);
	}

	//=============================tmp consts for test
	public static final String[] DB_COLUMNS = UserDao.class.getAnnotation(DBColumns.class).value();
	private static final String[][] DB_USER = {//
	{ "1", "Bill Gates", "bill@microsoft.com" },//
			{ "2", "Steven Jobs", "jobs@apple.com" },//
			{ "3", "Steven Jobs", "jobs2@apple.com" },//another guy called Jobs at apple company
	};
}
